<template>
  <div class="app-container">
    <!-- AI助手标题 -->
    <el-card class="ai-header">
      <div class="header-content">
        <h2>AI智能助手</h2>
        <p>智能编程助手，为您提供代码分析、优化建议和解题思路</p>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 左侧聊天区域 -->
      <el-col :span="16">
        <el-card class="chat-card">
          <div slot="header" class="chat-header">
            <span>AI对话</span>
            <el-button size="mini" @click="clearChat">清空对话</el-button>
          </div>
          
          <!-- 聊天消息区域 -->
          <div class="chat-messages" ref="chatMessages">
            <div 
              v-for="(message, index) in chatMessages" 
              :key="index"
              :class="['message', message.type]"
            >
              <div class="message-avatar">
                <i :class="message.type === 'user' ? 'el-icon-user' : 'el-icon-cpu'"></i>
              </div>
              <div class="message-content">
                <div class="message-text" v-html="formatMessage(message.content)"></div>
                <div class="message-time">{{ parseTime(message.time) }}</div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入您的问题，例如：如何优化这段代码的性能？"
              @keyup.enter.native="sendMessage"
            />
            <div class="input-actions">
              <el-button type="primary" @click="sendMessage" :loading="sending">
                发送
              </el-button>
              <el-button @click="uploadCode">上传代码</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧功能区域 -->
      <el-col :span="8">
        <!-- 快速问题 -->
        <el-card class="quick-questions">
          <div slot="header">快速问题</div>
          <div class="question-list">
            <el-button 
              v-for="question in quickQuestions" 
              :key="question.id"
              size="small"
              @click="askQuickQuestion(question.text)"
              class="question-btn"
            >
              {{ question.text }}
            </el-button>
          </div>
        </el-card>

        <!-- AI功能 -->
        <el-card class="ai-features">
          <div slot="header">AI功能</div>
          <div class="feature-list">
            <div 
              v-for="feature in aiFeatures" 
              :key="feature.id"
              class="feature-item"
              @click="useFeature(feature)"
            >
              <i :class="feature.icon"></i>
              <span>{{ feature.name }}</span>
            </div>
          </div>
        </el-card>

        <!-- 使用统计 -->
        <el-card class="usage-stats">
          <div slot="header">使用统计</div>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-label">今日对话</div>
              <div class="stat-value">{{ usageStats.todayChats }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">代码分析</div>
              <div class="stat-value">{{ usageStats.codeAnalysis }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">优化建议</div>
              <div class="stat-value">{{ usageStats.optimizations }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 代码上传对话框 -->
    <el-dialog title="上传代码分析" :visible.sync="codeUploadVisible" width="600px">
      <el-form :model="codeForm" label-width="100px">
        <el-form-item label="编程语言">
          <el-select v-model="codeForm.language" placeholder="请选择编程语言">
            <el-option label="C++" value="cpp" />
            <el-option label="Java" value="java" />
            <el-option label="Python" value="python" />
            <el-option label="C" value="c" />
            <el-option label="JavaScript" value="js" />
          </el-select>
        </el-form-item>
        <el-form-item label="代码内容">
          <el-input
            v-model="codeForm.code"
            type="textarea"
            :rows="15"
            placeholder="请粘贴您要分析的代码"
          />
        </el-form-item>
        <el-form-item label="分析类型">
          <el-checkbox-group v-model="codeForm.analysisTypes">
            <el-checkbox label="performance">性能分析</el-checkbox>
            <el-checkbox label="security">安全检查</el-checkbox>
            <el-checkbox label="readability">可读性分析</el-checkbox>
            <el-checkbox label="optimization">优化建议</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="codeUploadVisible = false">取消</el-button>
        <el-button type="primary" @click="analyzeCode">开始分析</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAiHint, getAiAnalysis, getAiOptimization } from "@/api/system/ai-assistant";

export default {
  name: "AiAssistant",
  data() {
    return {
      inputMessage: "",
      chatMessages: [],
      sending: false,
      codeUploadVisible: false,
      codeForm: {
        language: "cpp",
        code: "",
        analysisTypes: ["performance"]
      },
      quickQuestions: [
        { id: 1, text: "如何提高代码执行效率？" },
        { id: 2, text: "这段代码有什么问题？" },
        { id: 3, text: "如何优化内存使用？" },
        { id: 4, text: "推荐学习算法的方法" },
        { id: 5, text: "如何调试程序？" },
        { id: 6, text: "代码风格最佳实践" }
      ],
      aiFeatures: [
        { id: 1, name: "代码分析", icon: "el-icon-view", type: "analysis" },
        { id: 2, name: "性能优化", icon: "el-icon-speed", type: "optimization" },
        { id: 3, name: "安全检查", icon: "el-icon-warning", type: "security" },
        { id: 4, name: "算法解释", icon: "el-icon-reading", type: "algorithm" },
        { id: 5, name: "调试帮助", icon: "el-icon-tools", type: "debug" },
        { id: 6, name: "学习建议", icon: "el-icon-guide", type: "learning" }
      ],
      usageStats: {
        todayChats: 12,
        codeAnalysis: 8,
        optimizations: 5
      }
    };
  },
  mounted() {
    this.addWelcomeMessage();
  },
  methods: {
    /** 添加欢迎消息 */
    addWelcomeMessage() {
      this.chatMessages.push({
        type: 'ai',
        content: '您好！我是AI编程助手，可以帮您分析代码、提供优化建议、解答编程问题。请问有什么可以帮助您的吗？',
        time: new Date()
      });
    },
    /** 发送消息 */
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      
      // 添加用户消息
      this.chatMessages.push({
        type: 'user',
        content: this.inputMessage,
        time: new Date()
      });

      const userMessage = this.inputMessage;
      this.inputMessage = "";
      this.sending = true;

      // 模拟AI回复
      setTimeout(() => {
        this.chatMessages.push({
          type: 'ai',
          content: this.generateAIResponse(userMessage),
          time: new Date()
        });
        this.sending = false;
        this.scrollToBottom();
      }, 1000);
    },
    /** 生成AI回复 */
    generateAIResponse(userMessage) {
      const responses = [
        "这是一个很好的问题！让我为您详细分析一下...",
        "根据您的描述，我建议您可以尝试以下方法：",
        "这个问题涉及到几个关键点，我来为您逐一解释：",
        "从代码优化的角度来看，您可以考虑以下改进：",
        "这是一个常见的编程问题，解决方案如下："
      ];
      return responses[Math.floor(Math.random() * responses.length)] + 
             "<br><br>具体来说，您可以：<br>1. 检查算法复杂度<br>2. 优化数据结构使用<br>3. 减少不必要的计算<br>4. 使用更高效的库函数";
    },
    /** 快速问题 */
    askQuickQuestion(question) {
      this.inputMessage = question;
      this.sendMessage();
    },
    /** 使用AI功能 */
    useFeature(feature) {
      this.inputMessage = `请帮我进行${feature.name}`;
      this.sendMessage();
    },
    /** 上传代码 */
    uploadCode() {
      this.codeUploadVisible = true;
    },
    /** 分析代码 */
    analyzeCode() {
      if (!this.codeForm.code.trim()) {
        this.$message.warning("请输入代码内容");
        return;
      }

      this.codeUploadVisible = false;
      this.chatMessages.push({
        type: 'user',
        content: `请分析以下${this.codeForm.language}代码：<br><pre>${this.codeForm.code}</pre>`,
        time: new Date()
      });

      // 模拟代码分析
      setTimeout(() => {
        this.chatMessages.push({
          type: 'ai',
          content: this.generateCodeAnalysis(),
          time: new Date()
        });
        this.scrollToBottom();
      }, 2000);
    },
    /** 生成代码分析 */
    generateCodeAnalysis() {
      return `
        <div class="code-analysis">
          <h4>代码分析结果：</h4>
          <div class="analysis-item">
            <strong>时间复杂度：</strong> O(n²)，可以优化为 O(n log n)
          </div>
          <div class="analysis-item">
            <strong>空间复杂度：</strong> O(1)，空间使用合理
          </div>
          <div class="analysis-item">
            <strong>优化建议：</strong>
            <ul>
              <li>使用更高效的数据结构</li>
              <li>避免重复计算</li>
              <li>考虑使用缓存机制</li>
            </ul>
          </div>
        </div>
      `;
    },
    /** 清空对话 */
    clearChat() {
      this.$confirm('确定要清空所有对话记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.chatMessages = [];
        this.addWelcomeMessage();
      });
    },
    /** 滚动到底部 */
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatMessages;
        container.scrollTop = container.scrollHeight;
      });
    },
    /** 格式化消息内容 */
    formatMessage(content) {
      return content.replace(/\n/g, '<br>');
    },
    /** 时间格式化 */
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = cFormat || '{h}:{i}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        return value.toString().padStart(2, '0');
      });
      return time_str;
    }
  }
};
</script>

<style scoped>
.ai-header {
  margin-bottom: 20px;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.header-content p {
  margin: 10px 0 0 0;
  color: #909399;
}

.chat-card {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10px;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background-color: #409EFF;
  color: white;
}

.message.ai .message-avatar {
  background-color: #67C23A;
  color: white;
}

.message-content {
  max-width: 70%;
  background-color: white;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message.user .message-content {
  background-color: #409EFF;
  color: white;
}

.message-text {
  line-height: 1.5;
  margin-bottom: 5px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.chat-input {
  margin-top: auto;
}

.input-actions {
  margin-top: 10px;
  text-align: right;
}

.quick-questions {
  margin-bottom: 20px;
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-btn {
  text-align: left;
  justify-content: flex-start;
}

.ai-features {
  margin-bottom: 20px;
}

.feature-list {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.feature-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.feature-item:hover {
  background-color: #f5f7fa;
  border-color: #409EFF;
}

.feature-item i {
  margin-right: 8px;
  color: #409EFF;
}

.usage-stats {
  margin-bottom: 20px;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: bold;
  color: #409EFF;
  font-size: 18px;
}

.code-analysis {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.analysis-item {
  margin-bottom: 10px;
}

.analysis-item ul {
  margin: 5px 0;
  padding-left: 20px;
}

pre {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
}
</style> 